package com.kfm.base.net;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TCPSend {
    public static void main(String[] args) {
        try (Socket client = new Socket(InetAddress.getByName("localhost"), 9999);){
            // 连接成功
            OutputStream outputStream = client.getOutputStream();

            FileInputStream fis = new FileInputStream("C:\\Users\\10854\\Pictures\\cat.jpg");

            outputStream.write(fis.readAllBytes());

            client.shutdownOutput();

            // 接收来自服务端的反馈
            InputStream inputStream = client.getInputStream();

            byte[] bytes = inputStream.readAllBytes();

            System.out.println(new String(bytes));

            client.shutdownInput();

        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

class TCPReceive {

    public static void main(String[] args) {
        try (ServerSocket server = new ServerSocket(9999);){

            ThreadPoolExecutor pool = new ThreadPoolExecutor(5, 50, 0L, TimeUnit.NANOSECONDS, new SynchronousQueue<>(), new ThreadPoolExecutor.AbortPolicy());

            while (true){
                // 等待客户端连接
                Socket accept = server.accept();

                pool.execute(() -> {
                    System.out.println("接收到来自 " + accept.getInetAddress() + "的请求");
                    InputStream inputStream = null;
                    try {
                        inputStream = accept.getInputStream();
                        byte[] bytes = inputStream.readAllBytes();


                        FileOutputStream fos =  new FileOutputStream("D:\\socket\\" + accept.getInetAddress().getHostAddress() +".jpg");

                        fos.write(bytes);
                        fos.close();

                        System.out.println("接收到" + accept.getInetAddress() + " 文件：" + bytes.length + " byte");

                        // 返回信息
                        OutputStream outputStream = accept.getOutputStream();
                        outputStream.write("已收到，Over".getBytes());

                        accept.shutdownOutput();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                });
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}